package mvc.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mvc.bean.MvcBean;
import mvc.service.ActionBean;
import mvc.service.ActionObject;
import apache.ApplicationCache;

public class Action {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * post方法
	 * 
	 * @throws IOException
	 * @throws ServletException
	 */
	public void doPost(BufferedReader in, OutputStream out) throws Exception {
		// 对数据进行处理
		Map<String, String> map = hadleMessage(in);
		String path = map.get("path");
		path = path.split("/")[1];
		Map<String, MvcBean> mvcMap = (Map<String, MvcBean>) ApplicationCache
				.getInstance().get("mvc");
		MvcBean bean = mvcMap.get(path);
		ActionObject object = ActionBean.actionBean(bean.getBeanClass(), map);
		ActionInterface actionInterface = null;
		String type = bean.getType();
		String url = "";
		try {
			Class clazz = Class.forName(type);
			actionInterface = (ActionInterface) clazz.newInstance();
			url = actionInterface.execute(object, bean.getMap());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 输出
		PrintStream  writer = new PrintStream (out);
		File file = new File(url); // 资源文件
		System.out.println(file.getAbsolutePath());
		if (file != null && file.exists()) {
			InputStream fileIn = new FileInputStream(file);
			byte[] content = new byte[(int)file.length()];
			fileIn.read(content);
			writer.println("HTTP/1.0 200 queryfile");
			writer.println("content-length:"+content.length);
			writer.println();
			writer.write(content);
			writer.flush();
			writer.close();
			fileIn.close();
		} else { // 请求资源不存在，报404
			writer.println("HTTP/1.0 " );
			writer.println("content-type: text/html");
			writer.println();
			writer.println("<html>");
			writer.println("<title>error</title>");
			writer.println("<body>");
			writer.println("<h1>ErrorCode: " + "404" +" ErrorMessage: "+ "File Not Found!" + "</h1>");
			writer.println("</body>");
			writer.println("</html>");
			writer.flush();
			writer.close();
		}
	}

	/**
	 * get方法
	 * 
	 * @throws IOException
	 * @throws ServletException
	 */
	public void doGet(BufferedReader in, OutputStream out) throws Exception {
		this.doPost(in, out);
	}

	public Map<String, String> hadleMessage(BufferedReader reader) {
		Map<String, String> map = new HashMap<String, String>();
		// 对数据流进行处理放入map中
		try {
			String line = reader.readLine();
			String zhongLine = line.split(" ")[1];
			String resource = ""; // 请求地址
			String method = ""; // 请求方式
			if (line != null && !"".equals(line)) {
				method = getMethod(line);
			}
			System.out.println("resource=" + resource);
			System.out.println("method=" + method);
			//
			int contentLength = 0; // POST数据长度
			while ((line = reader.readLine()) != null) {
				if ("".equals(line))
					break;
				// System.out.println(line);
				if (line.startsWith("Content-Length")) { // 取得Content-Length
					contentLength = Integer.parseInt(line.substring(
							line.indexOf(':') + 1).trim());
				}
			}
			// 取得POST表单提交的内容
			String content = "";
			if (contentLength > 0 && method.equals("POST")) {
				System.out.println("POST -------------------- POST");
				char[] buf = new char[contentLength];
				for (int i = 0; i < contentLength; i++) {
					buf[i] = (char) reader.read();
				}
				content = new String(buf);
				map = this.setValue(content); // 保存进Map集合
				map.put("path", zhongLine);
			} else if (method.equals("GET")) {
				String[] s = zhongLine.split("\\?");
				map = this.setValue(s[1]); // 保存进Map集合
				map.put("path", s[0]);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	private Map<String, String> setValue(String content) {
		String[] keyValues = content.split("&");
		Map<String, String> map = new HashMap<String, String>();
		for (String s : keyValues) {
			String[] keyValue = s.split("="); 
			map.put(keyValue[0], keyValue[1]);
		}
		return map;
	}

	/**
	 * 获取请求方式
	 * 
	 * @param line
	 *            消息头第一行
	 * @return POST | GET
	 */
	private String getMethod(String line) {
		Pattern pattern = Pattern.compile("^(GET|POST)\\b");
		Matcher m = pattern.matcher(line);
		if (m.find())
			return m.group();
		return "";
	}
}
